﻿using System;
using System.Collections.Generic;

namespace Gp.Scripts.Core
{
    public class GameStateBlockInput : GameState
    {
        private GameState _lastState;
        private HashSet<object> _blockKeys;
        private readonly object _privateBlockKey;
        private readonly Func<GameState> _resumeCallback;

        /// <param name="blockKey">  </param>
        /// <param name="onResume"> 在恢复阻塞时调用，回调函数返回值为解除阻塞后的下一个 state。 </param>
        public GameStateBlockInput(object blockKey, Func<GameState> onResume)
        {
            _privateBlockKey = blockKey;
            _resumeCallback  = onResume;
        }


        public override GameState OnMakeTransition(GameState nextState)
        {
            GameState ret = this;
            switch (nextState)
            {
                case GameStateBlockInput blockState:
                    _blockKeys ??= new HashSet<object>();
                    _blockKeys.Add(blockState._privateBlockKey);
                    _blockKeys.Add(_privateBlockKey);
                    break;
                case GameStateBlockResume resumeState:
                {
                    if (SetAndCheckResume(resumeState.BlockKey))
                    {
                        ret = _resumeCallback();
                    }

                    break;
                }
                default:
                    ret = nextState;
                    break;
            }
            
            return ret;
        }

        /// <summary>
        /// 如果可恢复，则返回true
        /// </summary>
        private bool SetAndCheckResume(object key)
        {
            if (this._blockKeys != null)
            {
                _blockKeys.Remove(key);
                return _blockKeys.Count == 0;
            }
            else
            {
                return _privateBlockKey == key;
            }
        }
        
        
    }
}